<template>
  <div id="homePage">
    <!-- 搜索应用 -->
    <el-form inline :model="form" ref="formRef" label-width="80px">
      <el-form-item label="应用名称" prop="appName">
        <el-input v-model="form.appName" clearable placeholder="无限制" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="应用 id" prop="id">
        <el-input v-model="form.id" clearable placeholder="无限制" style="width: 300px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="default" @keydown.enter="keyDown" @click="doSearch"
          :loading="searchButtonIsLoading">搜索</el-button>
      </el-form-item>
      <!-- 分页 -->
      <el-form-item>
        <el-pagination @size-change="onSizeChange" @current-change="doSearch" v-model:currentPage="form.current"
          :page-sizes="[4, 8, 12, 24]" :page-size="form.pageSize" layout="total, sizes, prev, pager, next"
          :total="totalNum" background :pager-count="9" :disabled="paginationDisabled">
        </el-pagination>
      </el-form-item>
    </el-form>

    <!-- 应用卡片展示 -->
    <div id="appCardDisplay">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="item in tableData" :key="item.id">
          <el-card shadow="hover" :body-style="{ padding: '0px' }" @click="onCardClicked(item)">
            <!-- 卡片主体 -->
            <div class="cardBody">
              <img :src="item.appIcon">
              <div class="cardBadge">
                <div>{{ AppTypeEnumMap[AppTypeEnum[item?.appType] as keyof typeof AppTypeEnumMap] }}</div>
                <div>{{ ScoringStrategyEnumMap[ScoringStrategyEnum[item?.scoringStrategy] as keyof typeof ScoringStrategyEnumMap] }}</div>
              </div>
            </div>
            <!-- 卡片尾部 -->
            <div class="cardFooter">
              <!-- 用户头像 -->
              <div class="cardAvatar">
                <el-avatar :src="item.user?.userAvatar" />
              </div>
              <!-- 标题与描述 -->
              <div class="cardDetails">
                <div class="cardTitle">{{ item.appName }}</div>
                <div class="cardDesc">{{ item.appDesc }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>

  <!-- 对话框 -->
  <el-dialog id="appDetailDialog" v-model="dialogVisible" title="Shipping address" width="50%" top="5%">
    <template #header="{ close, titleId, titleClass }">
      <span :id="titleId"></span>
    </template>
    <!-- 卡片主体 -->
    <div class="my-header">
      <div class="dialogIcon">
        <img :src="appItem?.appIcon" />
      </div>

      <!-- 标题与描述 -->
      <div class="dialogTitle">{{ appItem?.appName }}</div>
      <el-descriptions :column="1">
        <el-descriptions-item label="应用 id">{{ appItem?.id }}</el-descriptions-item>
        <el-descriptions-item label="应用名称">{{ appItem?.appName }}</el-descriptions-item>
        <el-descriptions-item label="应用描述">{{ appItem?.appDesc }}</el-descriptions-item>
        <el-descriptions-item label="应用类型">
          {{ AppTypeEnumMap[AppTypeEnum[appItem?.appType] as keyof typeof AppTypeEnumMap] }}
        </el-descriptions-item>
        <el-descriptions-item label="评分规则">
          {{ ScoringStrategyEnumMap[ScoringStrategyEnum[appItem?.scoringStrategy] as keyof typeof ScoringStrategyEnumMap] }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ appItem?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="过审时间">{{ appItem?.reviewTime }}</el-descriptions-item>
        <el-descriptions-item label="创建用户">{{ appItem?.user?.userName }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <!-- 如果是自己的应用, 添加几个按钮 -->
        <template v-if="appItem?.user?.id === loginUserStore.loginUser.id">
          <el-button type="info" plain size="default" :icon="Edit" @click="doGoToAppPage">修改应用信息</el-button>
          <el-button type="info" plain size="default" :icon="Edit" @click="doGoToQuestionPage">修改题目信息</el-button>
          <el-button type="info" plain size="default" :icon="Edit" @click="doGoToScoringResultPage" v-if="appItem?.scoringStrategy !== ScoringStrategyEnum.AI">修改评分规则</el-button>
        </template>
        <el-button :icon="Share" type="success" @click="doShare">分享</el-button>
        <el-button :icon="loginUserStore.loginUser.userRole !== UserRoleEnum.NOT_LOGIN ? EditPen : ''" type="primary" @click="doGoToAnswerPage">
          {{ loginUserStore.loginUser.userRole !== UserRoleEnum.NOT_LOGIN ? "开始答题" : "查看题目"}}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <ShareDialog ref="shareDialog" :image-url="shareUrl"/>
</template>

<script setup lang="ts">
import { AppTypeEnum, AppTypeEnumMap, ResponseCodeEnum, ReviewStatusEnum, ScoringStrategyEnum, ScoringStrategyEnumMap, UserRoleEnum } from '@/enums';
import { ElMessage } from 'element-plus';
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue';
import { listAppVoByPageUsingPost } from '@/api/appController';
import { Edit, EditPen, Search, Share } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useLoginUserStore } from '@/stores/userStore';
import ShareDialog from '@/components/ShareDialog.vue';
import { useRoute } from 'vue-router';

const loginUserStore = useLoginUserStore();
const router = useRouter();
const { query } = useRoute();

// 表单查询请求数据
const form = reactive<API.AppQueryRequest>({
  id: undefined,
  appName: '',
  current: 1,
  pageSize: 8,
  reviewStatus: ReviewStatusEnum.PASSED
});

// 查询结果
const tableData = ref<API.AppVO[]>([]);

// 查询总数
const totalNum = ref(0);

// 查询按钮是否正在加载中
const searchButtonIsLoading = ref(false);

// 分页插件是否可用
const paginationDisabled = ref(true);

/**
 * 当一页的数据量改变时触发
 * @param pageSize 当前一页容量
 */
const onSizeChange = (pageSize: number) => {
  form.pageSize = pageSize;
  form.current = 1;
  doSearch();
}

/**
 * 执行查询
 */
const doSearch = async () => {
  // 点过一次查询按钮后, 才启用分页插件
  paginationDisabled.value = false;

  searchButtonIsLoading.value = true;
  const result = await listAppVoByPageUsingPost(form);
  searchButtonIsLoading.value = false;

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 更新表单数据与总数
    tableData.value = result.data.data?.records || [];
    totalNum.value = Number(result.data.data?.total) || 0;
  } else {
    ElMessage.error("获取数据失败: " + result.data.message);
  }
}

// 应用详情对话框是否显示
const dialogVisible = ref(false);

// 当前显示的应用信息
const appItem = ref<API.AppVO>();

/**
 * 点击卡片, 跳转到应用详情页
 * @param item 
 */
const onCardClicked = (item: API.AppVO) => {
  // 显示卡片
  dialogVisible.value = true
  // 信息给到 appItem
  appItem.value = item;
}

/**
 * 跳转到修改应用页面
 */
const doGoToAppPage = () => {
  router.push({
    name: '修改应用',
    params: {
      id: appItem.value?.id
    }
  })
}

/**
 * 跳转到修改题目页面
 */
const doGoToQuestionPage = () => {
  router.push({
    name: '编辑题目',
    params: {
      appId: appItem.value?.id
    }
  })
}

/**
 * 跳转到编辑评分规则页面
 */
const doGoToScoringResultPage = () => {
  router.push({
    name: '编辑评分策略',
    params: {
      appId: appItem.value?.id
    }
  })
}

/**
 * 跳转到做题页面
 */
const doGoToAnswerPage = () => {
  router.push({
    name: '答题',
    params: {
      appId: appItem.value?.id
    }
  })
}

/**
 * 监听键盘事件 
 * @param e 
 */
const keyDown = (e: any) => {
  if (e.keyCode == 13 || e.keyCode == 100) {
    doSearch()
  }
}

/**
 * 在首次加载时进行一次查询
 */
onMounted(() => {
  // 如果 query 存在, 将 query.id 赋值给 form.id
  if (query.queryId) {
    form.id = Number(query.queryId);
  }

  doSearch();

  // 将 enter 绑定到提交键, 参考 https://blog.csdn.net/cqlcqlcui123/article/details/130141190
  window.addEventListener('keydown', keyDown);
})

onUnmounted(() => {
  window.removeEventListener('keydown', keyDown);
})

// 分享按钮
const shareDialog = ref()

// 分享链接
const shareUrl = computed(() => `${window.location.protocol}//${window.location.host}/?queryId=${appItem.value?.id}`)

/**
 * 打开分享 dialog
 */
const doShare = () => {
  shareDialog.value.openDialog()
}

</script>

<style scoped lang="less">
#homePage {
  padding: 20px;
}

#appCardDisplay .el-card {
  cursor: pointer;
  margin: 10px 0;

  .cardBody {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    height: 200px;

    img {
      width: 100%;
      height: 100%;
      /* 截取图片, 保证填满并不变形 */
      object-fit: cover;
    }

    .cardBadge{
      font-size: 0.8em;
      position: absolute;
      right: 0;
      top: 0;

      div {
        padding: 5px;
        margin: 5px;
        background-color: rgba(78, 135, 234, 0.85);
        color: white;
        width: 70px;
        text-align: center;
        border-radius: 5px;
        font-weight: bold;
      }
    }
  }
  
  .cardFooter {
    border-top: 1px solid rgb(220, 223, 230);
    padding: 10px;
    display: flex;
    align-items: center;
    
    .cardAvatar {
      margin-right: 10px;
    }

    .cardDetails {
      width: 100%;

      .cardTitle {
        font-size: 1.3em;
        font-weight: bold;
        margin-bottom: 5px;
      }

      .cardDesc {
        color: rgb(153, 153, 153);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        width: 100%;
        height: 1.2em;
      }
    }
  }
}

#appDetailDialog {
  .dialogIcon {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;

    height: 300px;
    width: 100%;

    img {
      width: 80%;
      height: 100%;
      object-fit: cover;
    }
  }

  .dialogTitle {
    font-size: 2.5em;
    font-weight: bold;
    margin: 20px 0;
  }
}
</style>
